package com.szs.exception;

import com.szs.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/*
* 全局异常处理器
* */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /*@ExceptionHandler
    public Result handleException(Exception e) {
        log.error("程序出错了",e);
        return Result.error("出错了，请联系管路员");
    }*/
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("程序出错了",e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMessage = message.substring(i);
        String[] arr = errMessage.split(" ");//根据空格截取字符串
        return Result.error(arr[2]+"已存在");
    }
    /*
    * 删除班级异常
    * */
    @ExceptionHandler(ClassHasStudentsException.class)
    public Result handleClassHasStudentsException(ClassHasStudentsException e) {
        return Result.error("该班级下有学生，无法删除");
    }
    /*
    * 删除部门异常
    * */
    @ExceptionHandler(DeptHasEmpException.class)
    public Result handleDeptHasEmpException(DeptHasEmpException deptHasEmpException) {
        return Result.error("该部门下有员工，无法删除");
    }
}
